"use client"

import { useState } from "react"
import { motion } from "framer-motion"
import { useAuth } from '@/contexts/auth-context'
import Link from "next/link"
import { Search, Filter, Star, Eye, GitFork, Calendar, Award, Code } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"

const mockProjects = [
  {
    id: 1,
    title: "智能交通流量预测系统",
    description: "基于深度学习的城市交通流量预测模型，准确率达到95%以上",
    author: "Alex Chen",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "AI/ML",
    tags: ["深度学习", "交通预测", "TensorFlow", "Python"],
    stars: 234,
    forks: 45,
    views: 1520,
    createdAt: "2024-01-15",
    updatedAt: "2024-01-20",
    status: "完成",
    difficulty: "高级",
    thumbnail: "/placeholder.svg?height=200&width=300",
    competition: "天池智慧城市AI挑战赛",
    rank: "第2名",
  },
  {
    id: 2,
    title: "区块链碳交易平台",
    description: "去中心化的碳信用交易平台，支持智能合约自动执行",
    author: "Sarah Kim",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "Blockchain",
    tags: ["Solidity", "Web3", "React", "碳交易"],
    stars: 189,
    forks: 32,
    views: 980,
    createdAt: "2024-01-10",
    updatedAt: "2024-01-18",
    status: "进行中",
    difficulty: "中级",
    thumbnail: "/placeholder.svg?height=200&width=300",
    competition: "Devpost Climate Hackathon",
    rank: "第1名",
  },
  {
    id: 3,
    title: "实时语音情感分析API",
    description: "实时分析语音中的情感状态，支持多种语言和方言",
    author: "Mike Johnson",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "AI/NLP",
    tags: ["NLP", "语音识别", "情感分析", "FastAPI"],
    stars: 156,
    forks: 28,
    views: 750,
    createdAt: "2024-01-08",
    updatedAt: "2024-01-16",
    status: "完成",
    difficulty: "高级",
    thumbnail: "/placeholder.svg?height=200&width=300",
    competition: "Google AI Challenge",
    rank: "第3名",
  },
  {
    id: 4,
    title: "智能健康监测手环",
    description: "基于IoT的健康监测设备，实时监测心率、血压等生理指标",
    author: "Lisa Wang",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "IoT/Hardware",
    tags: ["IoT", "健康监测", "Arduino", "移动应用"],
    stars: 98,
    forks: 15,
    views: 420,
    createdAt: "2024-01-05",
    updatedAt: "2024-01-12",
    status: "进行中",
    difficulty: "中级",
    thumbnail: "/placeholder.svg?height=200&width=300",
    competition: "Microsoft IoT Challenge",
    rank: "参与中",
  },
  {
    id: 5,
    title: "AR教育游戏平台",
    description: "沉浸式AR技术让数学学习更有趣，适合中小学生使用",
    author: "Tom Zhang",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "AR/Education",
    tags: ["AR", "Unity", "教育", "游戏化"],
    stars: 267,
    forks: 52,
    views: 1340,
    createdAt: "2024-01-12",
    updatedAt: "2024-01-22",
    status: "完成",
    difficulty: "高级",
    thumbnail: "/placeholder.svg?height=200&width=300",
    competition: "教育科技创新大赛",
    rank: "第1名",
  },
  {
    id: 6,
    title: "智能农业监测系统",
    description: "基于传感器网络的智能农业监测，优化作物生长环境",
    author: "Emma Liu",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "IoT/Agriculture",
    tags: ["IoT", "农业", "传感器", "数据分析"],
    stars: 134,
    forks: 23,
    views: 680,
    createdAt: "2024-01-03",
    updatedAt: "2024-01-14",
    status: "完成",
    difficulty: "中级",
    thumbnail: "/placeholder.svg?height=200&width=300",
    competition: "智慧农业创新挑战赛",
    rank: "第2名",
  },
]

const categories = [
  "全部",
  "AI/ML",
  "Blockchain",
  "Web开发",
  "移动开发",
  "IoT/Hardware",
  "AR/VR",
  "数据科学",
  "游戏开发",
]

const statusOptions = ["全部", "完成", "进行中", "规划中"]
const difficultyOptions = ["全部", "初级", "中级", "高级"]

export default function ProjectsPage() {
  const { user, isLoading } = useAuth()
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("全部")
  const [selectedStatus, setSelectedStatus] = useState("全部")
  const [selectedDifficulty, setSelectedDifficulty] = useState("全部")
  const [sortBy, setSortBy] = useState("最新")

  const filteredProjects = mockProjects.filter((project) => {
    const matchesSearch =
      project.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      project.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      project.tags.some((tag) => tag.toLowerCase().includes(searchQuery.toLowerCase()))
    const matchesCategory = selectedCategory === "全部" || project.category === selectedCategory
    const matchesStatus = selectedStatus === "全部" || project.status === selectedStatus
    const matchesDifficulty = selectedDifficulty === "全部" || project.difficulty === selectedDifficulty

    return matchesSearch && matchesCategory && matchesStatus && matchesDifficulty
  })

  const getStatusColor = (status: string) => {
    switch (status) {
      case "完成":
        return "bg-green-500/20 text-green-400"
      case "进行中":
        return "bg-blue-500/20 text-blue-400"
      case "规划中":
        return "bg-yellow-500/20 text-yellow-400"
      default:
        return "bg-gray-500/20 text-gray-400"
    }
  }

  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty) {
      case "初级":
        return "bg-green-500/20 text-green-400"
      case "中级":
        return "bg-yellow-500/20 text-yellow-400"
      case "高级":
        return "bg-red-500/20 text-red-400"
      default:
        return "bg-gray-500/20 text-gray-400"
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 头部 */}
        <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="text-center mb-12">
          <h1 className="text-responsive-4xl font-bold mb-4 text-gradient-animate">项目展示</h1>
          <p className="text-responsive-xl" style={{ color: "white" }}>
            发现优秀项目，学习最佳实践，展示你的作品
          </p>
        </motion.div>

        {/* 搜索和筛选 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="mb-8"
        >
          <div className="flex flex-col md:flex-row gap-4 mb-6">
            <div className="flex-1 relative">
              <Search
                className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5"
                style={{ color: "white" }}
              />
              <Input
                placeholder="搜索项目、技术栈..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-12 glass-light border-0 placeholder-gray-400"
                style={{ color: "white" }}
              />
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                className="bg-transparent border-gray-500 hover:border-blue-400"
                style={{ color: "white" }}
              >
                <Filter className="w-4 h-4 mr-2" />
                筛选
              </Button>
            </div>
          </div>

          {/* 分类标签 */}
          <div className="flex flex-wrap gap-2 mb-4">
            {categories.map((category) => (
              <motion.div key={category} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                <Badge
                  variant={selectedCategory === category ? "default" : "outline"}
                  className={`cursor-pointer transition-all duration-300 ${
                    selectedCategory === category ? "bg-blue-500 text-white" : "border-gray-500 hover:border-blue-400"
                  }`}
                  style={{ color: selectedCategory === category ? "white" : "white" }}
                  onClick={() => setSelectedCategory(category)}
                >
                  {category}
                </Badge>
              </motion.div>
            ))}
          </div>

          {/* 状态和难度筛选 */}
          <div className="flex flex-wrap gap-2">
            {statusOptions.map((status) => (
              <Badge
                key={status}
                variant={selectedStatus === status ? "default" : "outline"}
                className={`cursor-pointer transition-all duration-300 ${
                  selectedStatus === status ? "bg-green-500 text-white" : "border-gray-500 hover:border-green-400"
                }`}
                style={{ color: "white" }}
                onClick={() => setSelectedStatus(status)}
              >
                {status}
              </Badge>
            ))}
            {difficultyOptions.map((difficulty) => (
              <Badge
                key={difficulty}
                variant={selectedDifficulty === difficulty ? "default" : "outline"}
                className={`cursor-pointer transition-all duration-300 ${
                  selectedDifficulty === difficulty
                    ? "bg-purple-500 text-white"
                    : "border-gray-500 hover:border-purple-400"
                }`}
                style={{ color: "white" }}
                onClick={() => setSelectedDifficulty(difficulty)}
              >
                {difficulty}
              </Badge>
            ))}
          </div>
        </motion.div>

        {/* 主要内容 */}
        <Tabs defaultValue="grid" className="w-full">
          <div className="flex items-center justify-between mb-6">
            <TabsList className="glass">
              <TabsTrigger value="grid" style={{ color: "white" }}>
                网格视图
              </TabsTrigger>
              <TabsTrigger value="list" style={{ color: "white" }}>
                列表视图
              </TabsTrigger>
            </TabsList>
            <div className="flex items-center gap-2">
              <span className="text-sm" style={{ color: "#d1d5db" }}>
                排序:
              </span>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="bg-transparent border border-gray-500 rounded px-2 py-1 text-sm"
                style={{ color: "white" }}
              >
                <option value="最新">最新</option>
                <option value="最热">最热</option>
                <option value="评分">评分</option>
              </select>
            </div>
          </div>

          {/* 网格视图 */}
          <TabsContent value="grid">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredProjects.map((project, index) => (
                <motion.div
                  key={project.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.1 }}
                >
                  <Card className="project-card card-hover h-full">
                    <div className="relative">
                      <img
                        src={project.thumbnail || "/placeholder.svg"}
                        alt={project.title}
                        className="w-full h-48 object-cover rounded-t-lg"
                      />
                      <div className="absolute top-3 left-3">
                        <Badge className={getStatusColor(project.status)}>{project.status}</Badge>
                      </div>
                      <div className="absolute top-3 right-3">
                        <Badge className={getDifficultyColor(project.difficulty)}>{project.difficulty}</Badge>
                      </div>
                      {project.rank && project.rank !== "参与中" && (
                        <div className="absolute bottom-3 left-3">
                          <Badge className="bg-yellow-500/20 text-yellow-400">
                            <Award className="w-3 h-3 mr-1" />
                            {project.rank}
                          </Badge>
                        </div>
                      )}
                    </div>

                    <CardContent className="p-4">
                      <h3
                        className="font-semibold text-lg mb-2 line-clamp-2 hover:text-blue-400 transition-colors cursor-pointer"
                        style={{ color: "white" }}
                      >
                        {project.title}
                      </h3>

                      <p className="text-sm mb-3 line-clamp-2" style={{ color: "#d1d5db" }}>
                        {project.description}
                      </p>

                      <div className="flex items-center gap-2 mb-3">
                        <Avatar className="w-6 h-6">
                          <AvatarImage src={project.avatar || "/placeholder.svg"} />
                          <AvatarFallback className="text-xs">{project.author[0]}</AvatarFallback>
                        </Avatar>
                        <span className="text-sm" style={{ color: "#d1d5db" }}>
                          {project.author}
                        </span>
                      </div>

                      <div className="flex items-center justify-between text-sm mb-3" style={{ color: "#9ca3af" }}>
                        <div className="flex items-center gap-1">
                          <Star className="w-4 h-4" />
                          <span>{project.stars}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <GitFork className="w-4 h-4" />
                          <span>{project.forks}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Eye className="w-4 h-4" />
                          <span>{project.views}</span>
                        </div>
                      </div>

                      <div className="flex flex-wrap gap-1 mb-4">
                        {project.tags.slice(0, 3).map((tag) => (
                          <Badge key={tag} variant="outline" className="text-xs" style={{ color: "white" }}>
                            {tag}
                          </Badge>
                        ))}
                        {project.tags.length > 3 && (
                          <Badge variant="outline" className="text-xs" style={{ color: "white" }}>
                            +{project.tags.length - 3}
                          </Badge>
                        )}
                      </div>

                      <div className="text-xs mb-4" style={{ color: "#9ca3af" }}>
                        <div>竞赛: {project.competition}</div>
                        <div>更新: {project.updatedAt}</div>
                      </div>

                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          className="flex-1 bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                          style={{ color: "white" }}
                        >
                          <Code className="w-4 h-4 mr-1" />
                          查看代码
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="bg-transparent border-gray-500 hover:border-blue-400"
                          style={{ color: "white" }}
                        >
                          <Star className="w-4 h-4" />
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </div>
          </TabsContent>

          {/* 列表视图 */}
          <TabsContent value="list">
            <div className="space-y-4">
              {filteredProjects.map((project, index) => (
                <motion.div
                  key={project.id}
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: index * 0.1 }}
                >
                  <Card className="project-card card-hover">
                    <CardContent className="p-6">
                      <div className="flex items-start gap-4">
                        <img
                          src={project.thumbnail || "/placeholder.svg"}
                          alt={project.title}
                          className="w-24 h-24 object-cover rounded-lg flex-shrink-0"
                        />
                        <div className="flex-1">
                          <div className="flex items-start justify-between mb-2">
                            <h3
                              className="font-semibold text-xl hover:text-blue-400 transition-colors cursor-pointer"
                              style={{ color: "white" }}
                            >
                              {project.title}
                            </h3>
                            <div className="flex items-center gap-2">
                              <Badge className={getStatusColor(project.status)}>{project.status}</Badge>
                              <Badge className={getDifficultyColor(project.difficulty)}>{project.difficulty}</Badge>
                            </div>
                          </div>

                          <p className="mb-3 line-clamp-2" style={{ color: "#d1d5db" }}>
                            {project.description}
                          </p>

                          <div className="flex items-center gap-4 mb-3">
                            <div className="flex items-center gap-2">
                              <Avatar className="w-6 h-6">
                                <AvatarImage src={project.avatar || "/placeholder.svg"} />
                                <AvatarFallback className="text-xs">{project.author[0]}</AvatarFallback>
                              </Avatar>
                              <span className="text-sm" style={{ color: "#d1d5db" }}>
                                {project.author}
                              </span>
                            </div>
                            <div className="flex items-center gap-4 text-sm" style={{ color: "#9ca3af" }}>
                              <div className="flex items-center gap-1">
                                <Star className="w-4 h-4" />
                                <span>{project.stars}</span>
                              </div>
                              <div className="flex items-center gap-1">
                                <GitFork className="w-4 h-4" />
                                <span>{project.forks}</span>
                              </div>
                              <div className="flex items-center gap-1">
                                <Eye className="w-4 h-4" />
                                <span>{project.views}</span>
                              </div>
                              <div className="flex items-center gap-1">
                                <Calendar className="w-4 h-4" />
                                <span>{project.updatedAt}</span>
                              </div>
                            </div>
                          </div>

                          <div className="flex items-center justify-between">
                            <div className="flex flex-wrap gap-1">
                              {project.tags.slice(0, 4).map((tag) => (
                                <Badge key={tag} variant="outline" className="text-xs" style={{ color: "white" }}>
                                  {tag}
                                </Badge>
                              ))}
                            </div>
                            <div className="flex gap-2">
                              <Button
                                size="sm"
                                className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                                style={{ color: "white" }}
                              >
                                <Code className="w-4 h-4 mr-1" />
                                查看代码
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                className="bg-transparent border-gray-500 hover:border-blue-400"
                                style={{ color: "white" }}
                              >
                                <Star className="w-4 h-4" />
                              </Button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
            </div>
          </TabsContent>
        </Tabs>

        {/* 空状态 */}
        {filteredProjects.length === 0 && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-center py-12">
            <div className="text-6xl mb-4">📁</div>
            <h3 className="text-xl font-semibold mb-2" style={{ color: "white" }}>
              没有找到匹配的项目
            </h3>
            <p style={{ color: "#d1d5db" }}>尝试调整筛选条件或搜索关键词</p>
          </motion.div>
        )}
      </div>
    </div>
  )
}
